package com.zgkj.Zip;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;

import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import com.zgkj.Zip.form.NoticeInfo;
import com.zgkj.Zip.form.NoticeListInf;
import com.zgkj.Zip.service.InsetDbService;
import com.zgkj.Zip.service.UploadFileService;
import com.zgkj.Zip.tools.DBUtil;
import com.zgkj.Zip.tools.FileList;
import com.zgkj.Zip.tools.FileOperate;
import com.zgkj.Zip.tools.TifToPDFUtil;
import com.zgkj.Zip.tools.XMLToBean;
import com.zgkj.Zip.tools.XMLUtil;

public class unzip  {

	private static final String version = "1.0.5";

	public static final String istest = "0";  //0 生产 1-测试 2 本地


//	//**中成
	public static final String unitid = "10007";
	public static final String mchntid = "330160910007";
	//**天昊
//	public static final String unitid = "10008";
//	public static final String mchntid = "330160900096";

//	橙知果
//	public static final String unitid = "10006";
//	public static final String mchntid = "330160910006";

//	上海启核
//	public static final String unitid = "10005";
//	public static final String mchntid = "330160910005";

	private static Logger log = Logger.getLogger(unzip.class);

	 public static synchronized void unzip(String zipFilename, String outputDirectory)
			throws IOException {
		String separator = System.getProperty("file.separator");
		File outFile = new File(outputDirectory);
		if (!outFile.exists()) {
			outFile.mkdirs();
		}
		ZipFile zipFile = new ZipFile(zipFilename);
		Enumeration en = zipFile.getEntries();
		ZipEntry zipEntry = null;
		while (en.hasMoreElements()) {
			zipEntry = (ZipEntry) en.nextElement();
			if (zipEntry.isDirectory()) {
				String dirName = zipEntry.getName();
				dirName = dirName.substring(0, dirName.length() - 1);
				File f = new File(outFile.getPath() + separator + dirName);
				f.mkdirs();
			} else {
				String strFilePath = outFile.getPath() + separator
						+ zipEntry.getName();
				File f = new File(strFilePath);
				if (!f.exists()) {
					String[] arrFolderName = zipEntry.getName().replaceAll("\\\\","/").split("/");
					String strRealFolder = "";
					for (int i = 0; i < (arrFolderName.length - 1); i++) {
						strRealFolder += arrFolderName[i] + separator;
					}
					strRealFolder = outFile.getPath() + separator
							+ strRealFolder;
					File tempDir = new File(strRealFolder);
					tempDir.mkdirs();
				}
				//////end///
				f.createNewFile();
				InputStream in = zipFile.getInputStream(zipEntry);
				FileOutputStream out = new FileOutputStream(f);
				try {
					int c;
					byte[] by = new byte[1024];
					while ((c = in.read(by)) != -1) {
						out.write(by, 0, c);
					}
				} catch (IOException e) {
					throw e;
				} finally {
					out.close();
					in.close();
				}
			}
		}
		zipFile.close();
	}

	 public static void main(String[] args) throws Exception  {
		DBUtil db = new DBUtil();
		log(unitid);
		log(mchntid);
		log(istest);
		HashMap versionMap = db.getRecord("select t.version,t.state,t.adddate from BIEXEVERSIONTB t where t.version='"+version+"'");
	    if (versionMap == null) {
	      log("该版本不存在，请联系智管科技的技术人员！");
	      return; }
	    if (!("0".equals(versionMap.get("state")))) {
	      log("该版本已经停用，请联系智管科技的技术人员索取最新版本！");
	      return;
	    }

	    //File directory = new File("C:\\Users\\KCF\\Desktop\\kcf\\");
		File directory = new File("");
		String filenameString  = directory.getCanonicalPath();
		File file=new File(filenameString);
		File[] tempList = file.listFiles();
		File file3=new File(filenameString+"\\hasdeal\\");
		if(!file3.exists()){
			file3.mkdirs();
		}
		File file4=new File(filenameString+"\\waitdeal\\");
		if(!file4.exists()){
			file4.mkdirs();
		}
		for (File file2 : tempList) {
			String filename = file2.getName();
			String filepath = file2.getPath();
			if(filename.toUpperCase().endsWith("ZIP")){
				unzip.unzip(filepath,file4.getPath());
				FileOperate.delFile(file2.getPath());
			}
		}
		File[] dclList = file4.listFiles();
		for (File file5 : dclList) {
			String file5nameString = file5.getName();
			FileList FileList = new FileList(file5);
			HashMap<String, Object> fileMap = FileList.getFilesmap();
			String listxmlpath = (String) fileMap.get("LISTXML");
			String gaxmlpath = (String) fileMap.get("GAXML");
			ArrayList<String> tifList = (ArrayList<String>) fileMap.get("TIFLIST");
			ArrayList<String> pdfList = (ArrayList<String>) fileMap.get("PDFLIST");
			NoticeInfo NoticeInfo = null;
			if(gaxmlpath!=null){
				 NoticeInfo  = XMLUtil.getNoticeInfo(gaxmlpath);
			}
			if(listxmlpath==null){
				continue;
			}
			XMLToBean XMLToBean = new XMLToBean(listxmlpath);
			NoticeListInf NoticeListInf = XMLToBean.getNoticelistinf();
			String pdfpathString = file5.getPath()+"\\"+file5nameString+".pdf";
			if(pdfList==null||pdfList.size()==0){
				TifToPDFUtil.tifToPdf(tifList.toArray(new String[tifList.size()]),pdfpathString);
			}else{
				if(!pdfList.contains(pdfpathString)){
					TifToPDFUtil.mergePdfFiles(pdfList.toArray(new String[pdfList.size()]),pdfpathString);
				}
			}

			//信息入库
			InsetDbService InsetDbService = new InsetDbService();
			if(InsetDbService.instert(NoticeInfo, NoticeListInf)){
				//pdf文件上传
				UploadFileService UploadFileService = new UploadFileService();
				com.zgkj.Zip.service.UploadFileService.uploadFileToSer(pdfpathString);
				//删除目录
				FileOperate.moveFolder(file5.getPath(), file3.getPath()+"//"+file5nameString);
			}

		}

	}
	 public static void log(String msg) {
		 	SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
	        String s = simpledateformat.format(Calendar.getInstance().getTime());
			String logString = s + ":"+msg;
			log.info(logString);
			System.out.println(logString);
		}

}
